﻿using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Personnels
{
    public class PersonnelSeachHander : IRequestHandler<PersonnelSeachCommand, ResultPage<Personnel>>
    {
        private readonly IBaseRepository<Personnel> _personnelRepository;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="personnelRepository"></param>
        /// <param name="mapper"></param>
        public PersonnelSeachHander(IBaseRepository<Personnel> personnelRepository, IMapper mapper)
        {
            _personnelRepository = personnelRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Personnel>> Handle(PersonnelSeachCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Personnel>() { Code = (int)CommonErrorCode.Search, TotalCount = 0, PagedCount = 0 };
            try
            {
                var personnelist = await (await _personnelRepository.GetAll()).ToListAsync();
                if (!string.IsNullOrEmpty(request.PersName))
                {
                    personnelist = personnelist.Where(p => p.PersName.Contains(request.PersName)).ToList();
                }
                if (request.DepartmentId > 0)
                {
                    personnelist = personnelist.Where(p => p.DepartmentId == request.DepartmentId).ToList();
                }
                if (!string.IsNullOrEmpty(request.StaffState))
                {
                    personnelist = personnelist.Where(p => p.StaffState == request.StaffState).ToList();
                }
                result.TotalCount = personnelist.Count;
                result.PagedCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                personnelist = personnelist.OrderByDescending(c => c.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = personnelist;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
